package org.example.projectdemo.controller;

/**
 * ClassName: CourseController
 * Package: org.example.projectdemo.controller
 * Description:
 *
 * @Author ZY
 * @Create 00:02
 * @Version 1.0
 */

import jakarta.validation.Valid;
import org.example.projectdemo.advice.ErrorResponse;
import org.example.projectdemo.model.entity.Course;
import org.example.projectdemo.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 课程管理控制器
 * 处理课程相关的HTTP请求
 */
@RestController
@RequestMapping("/api/courses")
public class CourseController {
    @Autowired
    private CourseService courseService;

    /**
     * 创建课程信息
     *
     * @param course 课程信息
     * @return 创建后的课程信息
     */
    @PostMapping
    public ResponseEntity<?> createCourse(@Valid @RequestBody Course course) {
        try {
            Course savedCourse = courseService.createCourse(course);
            return ResponseEntity.ok(savedCourse);
        } catch (IllegalArgumentException e) {
            ErrorResponse errorResponse = new ErrorResponse("COURSE_CONFLICT", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 更新课程信息
     *
     * @param id 课程ID
     * @param course 课程信息
     * @return 更新后的课程信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateCourse(@PathVariable Long id, 
                                               @Valid @RequestBody Course course) {
        course.setId(id);
        try {
            Course updatedCourse = courseService.updateCourse(course);
            return ResponseEntity.ok(updatedCourse);
        } catch (IllegalArgumentException e) {
            ErrorResponse errorResponse = new ErrorResponse("COURSE_CONFLICT", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    /**
     * 根据ID获取课程信息
     *
     * @param id 课程ID
     * @return 课程信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Course> getCourseById(@PathVariable Long id) {
        Optional<Course> course = courseService.getCourseById(id);
        return course.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 获取所有课程列表
     *
     * @return 所有课程列表
     */
    @GetMapping
    public ResponseEntity<List<Course>> getAllCourses() {
        List<Course> courses = courseService.getAllCourses();
        return ResponseEntity.ok(courses);
    }

    /**
     * 根据课程代码获取课程信息
     *
     * @param courseCode 课程代码
     * @return 课程信息
     */
    @GetMapping("/by-code/{courseCode}")
    public ResponseEntity<Course> getCourseByCode(@PathVariable String courseCode) {
        Optional<Course> course = courseService.getCourseByCode(courseCode);
        return course.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 根据教师姓名获取课程列表
     *
     * @param teacherName 教师姓名
     * @return 该教师的课程列表
     */
    @GetMapping("/by-teacher-name/{teacherName}")
    public ResponseEntity<List<Course>> getCoursesByTeacherName(@PathVariable String teacherName) {
        List<Course> courses = courseService.getCoursesByTeacherName(teacherName);
        return ResponseEntity.ok(courses);
    }

    /**
     * 根据星期几获取课程列表
     *
     * @param dayOfWeek 星期几 (1-7)
     * @return 指定星期几的课程列表
     */
    @GetMapping("/by-day/{dayOfWeek}")
    public ResponseEntity<List<Course>> getCoursesByDay(@PathVariable Byte dayOfWeek) {
        List<Course> courses = courseService.getCoursesByDayOfWeek(dayOfWeek);
        return ResponseEntity.ok(courses);
    }

    /**
     * 删除课程信息
     *
     * @param id 课程ID
     * @return 删除成功返回200
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCourse(@PathVariable Long id) {
        try {
            System.out.println("尝试删除课程，ID: " + id);
            
            if (!courseService.existsCourseById(id)) {
                System.out.println("课程不存在，ID: " + id);
                return ResponseEntity.notFound().build();
            }
            
            System.out.println("课程存在，开始删除，ID: " + id);
            courseService.deleteCourse(id);
            System.out.println("课程删除成功，ID: " + id);
            
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            System.err.println("删除课程异常，ID: " + id + ", 错误: " + e.getMessage());
            e.printStackTrace();
            ErrorResponse errorResponse = new ErrorResponse("DELETE_FAILED", "删除课程失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}